package cn.dw.web.servlet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cn.dw.domain.AccessToken;

public class TokenThread implements Runnable {
	public static String appId = "";
	public static String appSecret = "";
	public static AccessToken accessToken = null;

	public void run() {
		for (;;) {
			try {
				accessToken = getAccessToken();
				if (accessToken != null) {
					System.out.println(accessToken.getAccessToken());
					Thread.sleep(7000000L);
				} else {
					Thread.sleep(3000L);
				}
			} catch (Exception e) {
				System.out.println("发生异常：" + e.getMessage());
				e.printStackTrace();
				try {
					Thread.sleep(10000L);
				} catch (Exception localException1) {
				}
			}
		}
	}

	private AccessToken getAccessToken() {
		NetWorkHelp netHelper = new NetWorkHelp();
		String Url = String.format(
				"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s",
				new Object[] { appId, appSecret });
		String result = netHelper.getHttpsResponse(Url, "");
		System.out.println(result);

		JSONObject json = JSON.parseObject(result);
		AccessToken token = new AccessToken();
		token.setAccessToken(json.getString("access_token"));
		token.setExpiresin(json.getInteger("expires_in").intValue());
		return token;
	}

	public static String getAppId() {
		return appId;
	}

	public static void setAppId(String appId) {
		TokenThread.appId = appId;
	}

	public static String getAppSecret() {
		return appSecret;
	}

	public static void setAppSecret(String appSecret) {
		TokenThread.appSecret = appSecret;
	}
	
	
}
